package com.tanhua.server.service;


import com.tanhua.autoconfig.template.FaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.model.db.Question;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.QuestionVo;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.joda.time.DateTime;
import org.joda.time.Years;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *      新用户登录注册
 */
@Service
@Slf4j
public class UserInfoService {


    @DubboReference
    private UserInfoApi userInfoApi;//用户登录的API

    @Autowired
    private OssTemplate ossTemplate;//阿里云OSS云存储

    @Autowired
    private FaceTemplate faceTemplate;//百度云AI人脸识别


    /**
     *      利用从前端传回来的用户生日计算出用户年龄
     * @param birthday  前端传回来的用户生日
     * @return
     */
    private Integer getUserAge(String birthday){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date birthDay = sdf.parse(birthday);
            Years years = Years.yearsBetween(new DateTime(birthDay), DateTime.now());
            return years.getYears();
        } catch (ParseException e) {
            log.error("获取用户年龄失败!", e);
            return 0;
        }
    }

    /**
     * 新用户注册时设置用户的信息
     * @param userInfoVo
     */
    public void  Userinfo(UserInfoVo userInfoVo){
        UserInfo userInfo =  new UserInfo();
        BeanUtils.copyProperties(userInfoVo, userInfo);
        userInfo.setId(UserHolder.getUserId());
        userInfo.setAge(getUserAge(userInfo.getBirthday()));
        Long userInfoId = userInfoApi.AddUserInfo(userInfo);

    }

    /**
     *      图片上传到阿里云OSS存储
     * @param headPhoto
     *
     */
    public void upload(MultipartFile headPhoto) throws IOException {

        //调用第三方人脸检测，检测不到人脸需重新上传头像
        if (!faceTemplate.detect(headPhoto.getBytes())){
            throw new TanHuaException(ErrorResult.faceError());
        }
        //人脸检测通过，图片上传到第三方阿里云OSS存储
        String upload = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //更新用户头像信息
        UserInfo userInfo = new UserInfo();
        userInfo.setAvatar(upload);
        userInfo.setId(UserHolder.getUserId());
        userInfoApi.updeteUser(userInfo);
        log.info(upload);

    }

    /**
     * 获取用户信息
     * @param userId
     * @param huanxinId
     * @return
     */
    public UserInfoVo getuserinfo(Long userId, Long huanxinId) {
        if (userId == null) {
            userId=huanxinId;
        }
        if (huanxinId == null) {
            huanxinId=userId;
        }

        UserInfo userInfo = userInfoApi.getuserinfo(userId,huanxinId);
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, vo);
        vo.setAge(userInfo.getAge().toString());
        return vo;
    }

    /**
     * 更新用户信息
     * @param userInfoVo
     */
    public void updateUser(UserInfoVo userInfoVo) {
        userInfoVo.setId(UserHolder.getUserId());
        userInfoApi.updeteByuserId(userInfoVo);
    }

    /**
     * 更新用户头像
     * @param file
     */
    public void updateHeader(MultipartFile file) {
        try {
            boolean detect = faceTemplate.detect(file.getBytes());
            if (!detect) {
                throw new TanHuaException(ErrorResult.faceError());
            }
            String upload = ossTemplate.upload(file.getOriginalFilename(), file.getInputStream());
            UserInfo userInfo = new UserInfo();
            userInfo.setAvatar(upload);
            userInfo.setId(UserHolder.getUserId());
            userInfoApi.updateAvatar(userInfo);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 获取设置
     * @return
     */
    public SettingsVo getsettings() {

        SettingsVo getsetting = userInfoApi.getsetting(UserHolder.getUser());
        return getsetting;
    }

    /**
     * 移除黑名单
     * @param uid
     */
    public void deleteById(Long uid) {
        userInfoApi.deleteByid(uid);
    }
}
